<template>
	<el-dialog class="abow-dialog" :visible.sync="visible"
		:title="!bannerId ? '新增' : '修改'" :close-on-click-modal="false"
		:close-on-press-escape="false" width="650px" @close="closeFn">
		<el-dialog class="innerDialog" v-dialogDrag="innerCoverDialogDragFn" showScale custom-class="innerCoverDialog"
		      width="650px" :close-on-click-modal="false" :close-on-press-escape="false"
		      :title="innerTitle+'  '+innerTitleType"
		      :visible.sync="innerCoverVisible"
		      append-to-body>
			  <div class="d-flex a-cneter j-center">
				  <el-image :style="{width: innerCoverBodyWidth+'px',height: innerCoverBodyHeight+'px'}" :src="clickImg" fit="contain"></el-image>
			  </div>
		</el-dialog>
		<el-form class="form" :model="dataForm" :rules="dataRule" ref="dataForm" label-width="160px" size="medium" :inline="false"
			labelSuffix="：">
			<el-form-item prop="name" label="名称">
				<el-input clearable v-model="dataForm.name" placeholder="名称" />
			</el-form-item>
			<el-form-item prop="cover" label="图片">
				<div class="d-flex">
					<img v-if="dataForm.cover" class="d-flex mr-20 pointer" :src="dataForm.cover" @click.stop="lookImg(dataForm.cover,'图片')"
						style="width: 80px;height: auto;border-radius: 5px;">
					<div class="d-flex a-center">
						<el-button style="width: 80px;height: 40px;" v-if="$hasPermission('playlet:sts:uploadPath')"
							@click="uploadBtnFn('coverFileBtn','cover')">上传</el-button>
						<input type="file" ref="coverFileBtn" class="position-absolute top-0 left-0 d-none"
							@change="getFiles($event,'images')" />
					</div>
				</div>
			</el-form-item>
			<el-form-item prop="profile" label="简介" style="height: 150px;" >
				<el-input
					type="textarea"
					placeholder="请输入内容"
					v-model="dataForm.profile"
					maxlength="100"
					show-word-limit
					>
				</el-input>
			</el-form-item>
		
			<el-form-item prop="status" label="状态">
				<el-select clearable v-model="dataForm.status" placeholder="请选择">
					<el-option v-for="(item,index) in status" :key="index" :label="item.label" :value="item.value"></el-option>
				</el-select>
			</el-form-item>
		</el-form>
		<template slot="footer">
			<el-button @click="visible = false">{{ $t('views.public.cancel') }}</el-button>
			<el-button type="primary" @click="dataFormSubmitHandle()">{{ $t('views.public.confirm') }}</el-button>
		</template>
	</el-dialog>
</template>

<script>
	let that;
	import {
		debounce
	} from 'lodash'
	import {
		isEmail,
		isMobile
	} from '@/libs/validate'
	import schema from 'async-validator'
	import uploadTools from "./uploadTools";
	export default {
		mixins: [uploadTools],
		data() {
			return {
				innerCoverBodyWidth:650,
				innerCoverBodyHeight:450,
				bannerId:null,
				appletList:[],
				clickImg:'',
				innerTitle:'',
				innerTitleType:'',
				innerCoverVisible:false,
				status:[
				{
					value:0,
					label:'禁用',
				},
				{
					value:1,
					label:'正常',
				}],
				visible: false,
				deptList: [],
				deptListVisible: false,
				fullscreenLoading: false,
				roleList: [],
				roleIdListDefault: [],
				dataForm: {
					name: '', //轮播图名称 
					cover:'',//轮播图
					status: 1,//状态
					profile:''
				}
			}
		},
		created() {},
		mounted() {
			that = this;
		},
		computed: {
			dataRule() {
				return {
					name: [{
							required: true,
							message: '名称不能为空!',
							trigger: ['blur','change']
						}
					],
					cover: [{
							required: true,
							message: '封面图不能为空!',
							trigger: ['blur','change']
						}
					],
					status: [{
						required: true,
						message: '状态不能为空!',
						trigger: ['blur','change']
					}],
					profile: [{
							required: true,
							message: '简介不能为空!',
							trigger: ['blur','change']
						}
					],
				}
			}
		},
		methods: {
			innerCoverDialogDragFn(e){
				if(e){
					if(e.bodywidth){
						this.innerCoverBodyWidth = e.bodywidth;
					}
					if(e.bodyheight){
						this.innerCoverBodyHeight = e.bodyheight;
					}
				}
			},
			closeFn(){
				this.$refs.dataForm.resetFields();
			},
			lookImg(clickImg,type) {
				this.clickImg = clickImg;
				this.innerTitleType = type||'';
				this.innerCoverVisible = true;
			},
			async getFiles(event, fileType) {
				this['show' + fileType + 'Progress'] = false;
				console.log(event);
				const files = event.target.files;
				console.log(files);
				if (files.length) {
					const file = files[0];
					let checkRes = false;
					//图片
					if (fileType == 'images') {
						// 压缩图片后再上传
						const reader = new FileReader();
						reader.onload = (e) => {
							const img = new Image();
							img.onload = () => {
								const canvas = document.createElement('canvas');
								const ctx = canvas.getContext('2d');
								const maxWidth = 800; // 压缩后的最大宽度
								const maxHeight = 800; // 压缩后的最大高度
								let width = img.width;
								let height = img.height;
								// 如果宽度和高度超过最大值，则等比例缩放
								if (width > maxWidth || height > maxHeight) {
									const aspectRatio = width / height;
									if (width > height) {
										width = maxWidth;
										height = maxWidth / aspectRatio;
									} else {
										width = maxHeight * aspectRatio;
										height = maxHeight;
									}
								}
								canvas.width = width;
								canvas.height = height;
								ctx.drawImage(img, 0, 0, width, height);
								const compressedDataURL = canvas.toDataURL('image/jpeg',0.9); // 压缩后的图片数据URL，第二个参数表示压缩质量（0-1）
								// 将数据URL转换为Blob对象
								const blob = this.dataURLtoBlob(compressedDataURL);
								// 创建一个新的File对象
								const compressedFile = new File([blob], 'compressed_image.jpg', { type: 'image/jpeg' });
								// 在这里进行后续操作，上传压缩后的图片
								console.log(compressedFile);
								//检查文件格式和大小
								checkRes = this.checkPicFile(compressedFile, 10);
								this.uploadBefore(compressedFile,fileType,checkRes);
							};
							img.src = e.target.result;
						};
						reader.readAsDataURL(file);
					} else if (fileType == 'videos') {
						//视频
						checkRes = this.checkVideoFile(file, 500);
						this.uploadBefore(file,fileType,checkRes);
					}
				}
				event.target.value = '';
			},
			dataURLtoBlob(dataURL) {
				const byteString = atob(dataURL.split(',')[1]);
				const mimeString = dataURL.split(',')[0].split(':')[1].split(';')[0];
				const ab = new ArrayBuffer(byteString.length);
				const ia = new Uint8Array(ab);
				for (let i = 0; i < byteString.length; i++) {
					ia[i] = byteString.charCodeAt(i);
				}
				return new Blob([ab], {
					type: mimeString
				});
			},
			//获取上传密钥和文件路径再上传
			uploadBefore(file,fileType,checkRes){
				if (checkRes) {
					this.$axios.post(`/playlet/sts/uploadPath`, {
						type: fileType,
						suffix:this.getFileName(file.name)
					}).then(stsRes=>{
						if (typeof stsRes == 'object' && stsRes != null) {
							this.createOss(stsRes.token);
							this.handleUpload(file, fileType, stsRes.file_path + stsRes.file_name);
						}else{
							this.$message({
								message: '上传失败！',
								type: 'error',
								duration: 1500
							})
						}
					})
				}
			},
			handleUpload(file,fileType,uploadPath) {
				console.log('handleUploadhandleUpload');
				// 获取文件的后缀名
				// let objName = getFileNameUUID()
				var obj = file.name;
				var index = obj.lastIndexOf(".");
				obj = obj.substring(index, obj.length);
				// 生成的文件名，保留文件后缀名，进行拼接      
				let objName = this.getFileNameUUID() + this.getFileName(file.name);
				// 分片上传文件
				console.log(this.client);
				console.log(uploadPath);
				console.log(file);
				this.client.multipartUpload(`${uploadPath}`, file,{
					progress: async function(p) {
						that['show'+fileType+'Progress'] = true;
						that.percentage = Math.floor(p * 100);
					}
				}).then(clientRes => {
					console.log(clientRes, 'res')
					if(typeof clientRes == 'object' && clientRes!=null){
						if(typeof clientRes.res == 'object' && clientRes.res!=null){
							if(Array.isArray(clientRes.res.requestUrls)){
								if(clientRes.res.requestUrls.length){
									let requestUrl = this.removeUrlParams(clientRes.res.requestUrls[0]);
									if(!requestUrl){
										return this.$message({
											message: '上传失败！链接为空',
											type: 'error',
											duration: 1500
										})
									}
									if(fileType == 'images'){
										this.$set(this.dataForm, this.field, requestUrl);
									}else if(fileType == 'videos'){
										let video_cover = requestUrl+"?x-oss-process=video/snapshot,t_1000,f_jpg,w_0,h_0,m_fast,ar_auto";
										console.log(requestUrl);
										this.$set(this.dataForm, this.field, requestUrl);
										console.log(this.dataForm);
										this.videoOptions.video.url = requestUrl;
										this.videoOptions.video.pic = video_cover;
									}
									this.$refs.dataForm.validateField(this.field);
									this['show'+fileType+'Progress'] = false;
									return this.$message({
										message: '上传成功！',
										type: 'success',
										duration: 1500
									})
								}
							}
						}
					}
					this['show'+fileType+'Progress'] = false;
					this.$message({
						message: '上传失败！',
						type: 'error',
						duration: 1500
					})
				}).catch(err=>{
					console.log(err);
					this['show'+fileType+'Progress'] = false;
					this.$message({
						message: '上传失败！',
						type: 'error',
						duration: 1500
					})
				})
			},
			uploadBtnFn(fileBtn, field) {
				this.field = field;
				this.$refs[fileBtn].click();
			},
			init() {
				this.visible = true;
				this.$nextTick(() => {
					this.$refs.dataForm.resetFields();
				})
			},
			update(row) {
				this.visible = true
				this.$nextTick(() => {
					this.$refs.dataForm.resetFields();
					this.dataForm = Object.assign({}, row)
				})
			},

			// 所属部门树, 选中
			deptListTreeCurrentChangeHandle(data, node) {
				this.dataForm.deptId = data.deptId
				this.dataForm.deptName = data.name
				this.deptListVisible = false
			},
			// 表单提交
			dataFormSubmitHandle: debounce(function() {
				console.log('表单提交');
				this.$refs.dataForm.validate((valid) => {
					console.log(valid + '--+++++-----------')
					if (!valid) {
						return false
					}
					console.log(this.dataForm);
					this.$axios.post(this.bannerId?`/api/playlet/actor/update/${this.bannerId}`:'/api/playlet/actor/create', this.dataForm).then(res => {
						this.$message({
							message: this.$t('views.public.success'),
							type: 'success',
							duration: 500,
							onClose: () => {
								this.visible = false;
								this.$emit('refreshDataList');
							}
						})
					}).catch(() => {})
				})
			}, 1000, {
				leading: true,
				trailing: false
			})
		}
	}
</script>

<style lang="scss" scoped>
	.form{
		width: 540px;
	}
	.innerDialog{
		:deep(.el-dialog__body){
			padding: 0px!important;
		}
		:deep(.el-dialog__header){
			padding: 20px!important;
		}
	}
	:deep(.el-dialog__headerbtn){
		font-size: 25px!important;
		top:15px;
	}
	:deep(.el-textarea__inner){
		min-height: 140px !important;
		max-height: 140px !important;
	}
</style>